package middleware

import (
	"strings"

	"github.com/kataras/iris/v12"

	"go_iot/pkg/util"
)

func Authorization(ctx iris.Context) {

	if ctx.Path() == "/client/login" {

		ctx.Next()
		return
	}

	auth := ctx.GetHeader("Authorization")
	if auth == "" {
		ctx.StopWithJSON(iris.StatusUnauthorized, iris.Map{
			"message": "Missing authorization header",
		})
		return
	}

	tokenString := strings.Replace(auth, "Bearer ", "", 1)
	if tokenString == "" {
		ctx.StopWithJSON(iris.StatusUnauthorized, iris.Map{
			"message": "Invalid token format",
		})
		return
	}
	mc, err := util.ParseToken(tokenString)
	if err != nil {
		ctx.StopWithJSON(iris.StatusUnauthorized, iris.Map{
			"message": err.Error(),
		})
		return
	}
	ctx.Values().Set("client", mc.ClientId)

	ctx.Next()
}
